import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect:'/home'
    },
    {
      path: '/layout',
      name: 'layout',
      component: () => import('@/components/layout/index'),
      children: [{
          path:'/home',
          name:'home',
          component: () => import('@/views/home')
      }]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login')
    }
  ]
})
router.beforeEach((to, from, next) => {
  const hasAuth = localStorage.getItem('login')
  if (to.name === 'login' && hasAuth) {
    next({ name: 'home' })
    return
  }
  if (to.name !== 'login' && !hasAuth) {
    next({ name: 'login' })
    return
  }
  next()
})
export default router
